package logic

import (
	"context"
	"errors"
	"manuscriptservice/model/mysql"

	"manuscriptservice/manuscriptservicerpc/internal/svc"
	"manuscriptservice/manuscriptservicerpc/manuscriptservicerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ManuscriptAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManuscriptAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManuscriptAddLogic {
	return &ManuscriptAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ManuscriptAddLogic) ManuscriptAdd(in *manuscriptservicerpc.ManuscriptAddRequest) (*manuscriptservicerpc.ManuscriptAddResponse, error) {
	// todo: add your logic here and delete this line
	var findtitle mysql.Manuscript
	begin := mysql.DB.Begin()
	err := findtitle.FindTitle(begin, in.Title)
	if err == nil {
		begin.Rollback()
		return nil, errors.New("已经存在")
	}
	typer := mysql.Typer{
		TyperName: in.TypeName,
	}
	err = typer.FindTyper(begin, in.TypeName)
	if err != nil {
		begin.Rollback()
		return nil, errors.New("类型添加失败")
	}
	data := mysql.Manuscript{
		Title:   in.Title,
		Content: in.Content,
		TyperId: int(typer.ID),
	}
	err = data.ManuscriptAdd(begin)
	if err != nil {
		begin.Rollback()
		return nil, errors.New("添加失败")
	}
	begin.Commit()
	return &manuscriptservicerpc.ManuscriptAddResponse{
		ManuscriptId: int64(data.ID),
	}, nil
}
